//
//  QRCodeViewController.m
//  weibo
//
//  Created by hp on 16/4/26.
//  Copyright © 2016年 hp. All rights reserved.
//

#import "QRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface QRCodeViewController() <AVCaptureMetadataOutputObjectsDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topCons;
@property (weak, nonatomic) IBOutlet UIImageView *scanView;

// 扫描会话
@property (nonatomic, strong) AVCaptureSession *session;
// 输入设备
@property (nonatomic, strong) AVCaptureDeviceInput *inputDevice;
// 输出对象
@property (nonatomic, strong) AVCaptureMetadataOutput *outPut;

@property (weak, nonatomic) IBOutlet UILabel *resultLabel;

// 预览层
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
// 绘制层
@property (nonatomic, strong) CALayer *drawLayer;

@end

@implementation QRCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self startAnimation];
    [self startScan];
}



#pragma mark - 扫描动画
- (void)startAnimation
{

    self.topCons.constant = -300;
    [self.scanView layoutIfNeeded];

    [UIView animateWithDuration:2 animations:^{
        [UIView setAnimationRepeatCount:MAXFLOAT];
        self.topCons.constant = 10;
        // 父视图去刷新，因为让self.scanView刷新的话，不起作用
        [self.scanView.superview layoutIfNeeded];
    }];
}

#pragma mark - 懒加载

- (CALayer *)drawLayer
{
    if (_drawLayer==nil) {
        _drawLayer = [[CALayer alloc] init];
    }
    return _drawLayer;
}

- (AVCaptureVideoPreviewLayer *)previewLayer
{
    if (_previewLayer==nil) {
        _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
        _previewLayer.frame = [UIScreen mainScreen].bounds;
    }
    return _previewLayer;
}

- (AVCaptureSession *)session
{
    if (_session==nil) {
        _session = [[AVCaptureSession alloc] init];
    }
    return _session;
}

- (AVCaptureDeviceInput *)inputDevice
{
    if (_inputDevice==nil) {
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error;
        _inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
        if (error!=nil) {
            NSLog(@"%@",error.localizedDescription);
        }
    }
    return _inputDevice;
}

- (AVCaptureMetadataOutput *)outPut
{
    if (_outPut==nil) {
        _outPut = [[AVCaptureMetadataOutput alloc] init];
    }
    return  _outPut;
}
#pragma mark - 扫描二维码
- (void)startScan
{
    // 1、 判断能否将输入加入到会话
    if (![self.session canAddInput:self.inputDevice]) {
        return;
    }
    // 2、判断能否将输出加入到会话
    if (![self.session canAddOutput:self.outPut]) {
        return;
    }
    // 加入到会话
    [self.session addInput:self.inputDevice];
    [self.session addOutput:self.outPut];
    // 设置能够解析到的数据类型
    self.outPut.metadataObjectTypes = self.outPut.availableMetadataObjectTypes;
    NSLog(@"%@",self.outPut.availableMetadataObjectTypes);
    
    // 设置输出的代理
    [self.outPut setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 添加预览层
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    //添加绘制层
    [self.previewLayer addSublayer:self.drawLayer];
    // 让session开始工作
    [self.session startRunning];
}
#pragma mark - 扫描输出结果
// 扫描到结果的时候
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [self clearDrawLayer];
    
    NSLog(@"%@",metadataObjects);
    AVMetadataMachineReadableCodeObject *result = metadataObjects.lastObject;
    self.resultLabel.text = result.stringValue;
    // 转成坐标信息(二维码的边框位置数据)
    AVMetadataMachineReadableCodeObject *codeObject = (AVMetadataMachineReadableCodeObject *)[self.previewLayer transformedMetadataObjectForMetadataObject:result];
    // 绘制
    [self drawCorners:codeObject];
}

// 进行绘制
- (void)drawCorners:(AVMetadataMachineReadableCodeObject *)codeObject
{
    if (codeObject.corners==nil||codeObject.corners.count<1) {
        return;
    }
    
    
    // 贝塞尔曲线
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    CGPoint point;
    int index = 0;
    NSArray *corners = codeObject.corners;
    // 第一个点
    CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)corners[index++], &point); // 字典->CGPoint;
    [bezierPath moveToPoint:point];
    while (index<corners.count) {
        CGPointMakeWithDictionaryRepresentation((__bridge CFDictionaryRef)corners[index++], &point);
        [bezierPath addLineToPoint:point];
    }
    
    // 封闭路径
    [bezierPath closePath];
    // 绘制层
//    CAShapeLayer 是CALayer 的子类，给它设置路径就会进行绘制
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.lineWidth = 4;
    shapeLayer.strokeColor = [UIColor redColor].CGColor;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.path = bezierPath.CGPath;
    
    [self.drawLayer addSublayer:shapeLayer];
    
    
}

- (void)clearDrawLayer
{
    if (self.drawLayer.sublayers!=nil||self.drawLayer.sublayers.count>0) {
        for (CALayer *layer in self.drawLayer.sublayers) {
            [layer removeFromSuperlayer];
        }
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
